var express = require('express');
var router = express.Router();
var shortUrlDao = require('../dao/short_url.js');
var UserToken = require('../db/user_tokens.js');

router.post('/setUrl', function(req, res, next) {
    var par = paramAll(req);
    if(!par.key){
        res.json(new ERR('缺少 key ！', 400));
        return;
    }
    if(!par.token){
        res.json(new ERR('token不为空 ！', 400));
        return;
    }
    UserToken.checkUserLogin(par.token, function (err, code, userInfo) {
        if (err) {
            res.json(new ERR(err, code));
            return;
        }
        par.uid_own = userInfo.uid;
        par.url = 'http://usuz.cc/l1/' + uidToCode(userInfo.uid) + '/wxBind.html';

        shortUrlDao.setUrl(par, function (err, result) {
            if(err){
                res.json(new ERR(err, 400));
                return;
            }
            res.json(new PKG(result));
        })
    });
});

router.get('/:key', function(req, res, next) {
    var par = paramAll(req);
    if(!par.key){
        res.json(new ERR('缺少 key！', 400));
        return;
    }
    shortUrlDao.getUrl(par, function (err, result) {
        if(err || !result){
            res.json(new ERR(err, 400));
            return;
        }
        if(!result.length){
            res.redirect('http://usuz.cc/usuzLogin.html?next=setUrl&key=' + par.key);
            return;
        }
        var url = result[0].url;
        res.redirect(url);
    });
});



module.exports = router;
